<template>
  <div class="system-notice-container">
    <div class="page-header">
      <h2>系统通知管理</h2>
      <div class="header-content">
        <div class="search-container">
          <el-input
            v-model="searchQuery"
            placeholder="请输入通知标题"
            class="search-input"
            @keyup.enter="searchNotice"
            clearable
          >
            <template #append>
              <el-button @click="searchNotice" icon="Search"></el-button>
            </template>
          </el-input>
        </div>
        <div class="filter-container">
          <el-select v-model="filterType" placeholder="通知类型" clearable @change="handleFilterChange">
            <el-option label="系统通知" value="system" />
            <el-option label="活动通知" value="activity" />
            <el-option label="提醒通知" value="reminder" />
          </el-select>
          <el-select v-model="filterStatus" placeholder="通知状态" clearable @change="handleFilterChange">
            <el-option label="未读" value="unread" />
            <el-option label="已读" value="read" />
          </el-select>
        </div>
        <div class="batch-actions">
          <el-button type="primary" @click="handleBatchRead" :disabled="!selectedNotices.length">
            批量标记已读
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedNotices.length">
            批量删除
          </el-button>
        </div>
        <el-button type="primary" class="add-btn" @click="showAddDialog">添加通知</el-button>
      </div>
    </div>

    <div class="notice-table">
      <el-table
        :data="filteredNotices"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="notificationId" label="通知ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column prop="content" label="内容" min-width="200">
          <template #default="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.content"
              placement="top"
              :show-after="500"
            >
              <span class="content-preview">{{ scope.row.content }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="readTime" label="阅读时间" width="160">
          <template #default="scope">
            {{ scope.row.readTime ? formatDate(scope.row.readTime) : '未读' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'unread' ? 'danger' : 'success'">
              {{ scope.row.status === 'unread' ? '未读' : '已读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handlePreview(scope.row)"
            >
              预览
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row.notification_id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑通知' : '添加通知'"
      width="600px"
    >
      <el-form :model="currentNotice" label-width="80px">
        <el-form-item label="标题" required>
          <el-input v-model="currentNotice.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input
            v-model="currentNotice.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容"
          />
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="currentNotice.type" placeholder="请选择通知类型">
            <el-option label="系统通知" value="system" />
            <el-option label="活动通知" value="activity" />
            <el-option label="提醒通知" value="reminder" />
          </el-select>
        </el-form-item>
        <el-form-item label="接收用户" required>
          <el-select
            v-model="currentNotice.userId"
            placeholder="请选择接收用户"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.userName"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      title="通知预览"
      width="500px"
    >
      <div class="notice-preview">
        <h3>{{ previewNotice.title }}</h3>
        <div class="notice-meta">
          <span>类型：{{ getTypeLabel(previewNotice.type) }}</span>
          <span>创建时间：{{ formatDate(previewNotice.createTime) }}</span>
        </div>
        <div class="notice-content">
          {{ previewNotice.content }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchQuery = ref("")
const filterType = ref("")
const filterStatus = ref("")
const noticeList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const isEdit = ref(false)
const showDialog = ref(false)
const showPreviewDialog = ref(false)
const selectedNotices = ref([])
const userSearchLoading = ref(false)
const userOptions = ref([])
const previewNotice = ref({})


const currentNotice = ref({
  notificationId: '',
  title: '',
  content: '',
  createTime: '',
  readTime: '',
  status: 'unread',
  type: 'system',
  userId: ''
})

// 过滤后的通知列表
const filteredNotices = computed(() => {
  let result = noticeList.value

  if (filterType.value) {
    result = result.filter(notice => notice.type === filterType.value)
  }
  if (filterStatus.value) {
    result = result.filter(notice => notice.status === filterStatus.value)
  }
  if (searchQuery.value) {
    result = result.filter(notice => 
      notice.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  return result
})

// 获取通知类型标签样式
const getTypeTagType = (type) => {
  const types = {
    system: 'info',
    activity: 'success',
    reminder: 'warning'
  }
  return types[type] || 'info'
}

// 获取通知类型显示文本
const getTypeLabel = (type) => {
  const labels = {
    system: '系统通知',
    activity: '活动通知',
    reminder: '提醒通知'
  }
  return labels[type] || type
}

// 搜索通知
const searchNotice = async () => {
  try {
    const response = await axios.get(`/systemNotice/searchNotice?title=${searchQuery.value}`)
    if (response.code === 200) {
      noticeList.value = response.data.data || []
      total.value = noticeList.value.length
    }
  } catch (error) {
    console.error("搜索失败:", error)
    ElMessage.error('搜索失败')
  }
}

// 获取通知列表
const fetchNoticeList = async () => {
  try {
    const response = await axios.get('/systemNotice/NoticeList')
    if (response.code === 200) {
      noticeList.value = response.data || []
      console.log(noticeList.value);
      
      total.value = noticeList.value.length
      filteredNotices.value = [...noticeList.value]
    }
  } catch (err) {
    ElMessage.error('获取通知列表失败')
  }
}

// 切换通知状态
const toggleReadStatus = async (notice) => {
  const originalStatus = notice.status
  try {
    const response = await axios.put('/systemNotice/updateStatus', {
      notificationId: notice.notificationId,
      status: originalStatus === 'unread' ? 'read' : 'unread',
      readTime: originalStatus === 'unread' ? new Date() : null
    })

    if (response.code === 200) {
      notice.status = originalStatus === 'unread' ? 'read' : 'unread'
      notice.readTime = originalStatus === 'unread' ? new Date() : null
      ElMessage.success('状态更新成功')
      await fetchNoticeList()
    }
  } catch (err) {
    notice.status = originalStatus
    ElMessage.error('状态更新失败')
  }
}

// 批量标记已读
const handleBatchRead = async () => {
  if (!selectedNotices.value.length) return

  try {
    await ElMessageBox.confirm('确定要将选中的通知标记为已读吗？', '提示', {
      type: 'warning'
    })

    const promises = selectedNotices.value.map(notice => 
      axios.put('/systemNotice/updateStatus', {
        notification_id: notice.notification_id,
        status: 'read',
        readTime: new Date()
      })
    )

    await Promise.all(promises)
    ElMessage.success('批量标记已读成功')
    await fetchNoticeList()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('批量标记已读失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedNotices.value.length) return

  try {
    await ElMessageBox.confirm('确定要删除选中的通知吗？', '提示', {
      type: 'warning'
    })

    const promises = selectedNotices.value.map(notice =>
      axios.delete(`/systemNotice/delete/${notice.notification_id}`)
    )

    await Promise.all(promises)
    ElMessage.success('批量删除成功')
    await fetchNoticeList()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedNotices.value = selection
}

// 过滤条件变化
const handleFilterChange = () => {
  currentPage.value = 1
}

// 搜索用户
const searchUsers = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      const response = await axios.get(`/systemNotice/searchNotice?userName=${query}`)
      if (response.code === 200) {        
        userOptions.value = response.data || []
      }
    } catch (error) {
      console.error('搜索用户失败:', error)
    } finally {
      userSearchLoading.value = false
    }
  } else {
    userOptions.value = []
  }
}

// 预览通知
const handlePreview = (notice) => {
  previewNotice.value = { ...notice }
  showPreviewDialog.value = true
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  currentNotice.value = {
    notificationId: null,
    title: '',
    content: '',
    createTime: new Date().toISOString(),
    readTime: null,
    status: 'unread',
    type: 'system',
    userId: null
  }
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
  currentNotice.value = {
    notificationId: null,
    title: '',
    content: '',
    createTime: '',
    readTime: null,
    status: 'unread',
    type: 'system',
    userId: null
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleString()
}

// 分页处理
const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 保存通知
const handleSave = async () => {
  if (!currentNotice.value.title || !currentNotice.value.content || !currentNotice.value.userId) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    let response
    if (isEdit.value) {
      response = await axios.put('/systemNotice/update', currentNotice.value)
    } else {
      response = await axios.post('/systemNotice/add', currentNotice.value)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      closeDialog()
      await fetchNoticeList()
    }
  } catch (err) {
    ElMessage.error('操作失败')
    console.error(err)
  }
}

// 编辑通知
const handleEdit = (notice) => {
  isEdit.value = true
  currentNotice.value = { ...notice }
  showDialog.value = true
}

// 删除通知
const handleDelete = async (notification_id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      type: 'warning'
    })

    const response = await axios.delete(`/systemNotice/delete/${notification_id}`)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await fetchNoticeList()
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchNoticeList()
})
</script>

<style scoped>
.system-notice-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: 16px;
}

.search-container {
  width: 300px;
}

.filter-container {
  display: flex;
  gap: 16px;
}

.batch-actions {
  display: flex;
  gap: 8px;
}

.notice-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 16px;
}

.content-preview {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notice-preview {
  padding: 16px;
}

.notice-preview h3 {
  margin: 0 0 16px;
  color: #303133;
}

.notice-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  color: #909399;
  font-size: 14px;
}

.notice-content {
  line-height: 1.6;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-select) {
  width: 100%;
}
</style>
